/* eslint-disable default-case */
import {
  Button,
  Tabs,
  Input,
  Select,
  Image,
  Tag,
  Switch,
  Popconfirm,
  Upload,
} from "antd";
import {
  FieldTimeOutlined,
  DeleteOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import React, { useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import CommonPage from "@/components/page/CommonPage";
import Add from "@/components/svg/action-slot-icon/Add";
import DeleteOne from "@/components/svg/action-slot-icon/Delete_One";
import Exist from "@/components/svg/action-slot-icon/Exist";
import Enter from "@/components/svg/action-slot-icon/Enter";
import CrudTable from "@/components/table/CrudTable";
import QueryBarItem from "@/components/query-bar/QueryBarItem";
import styled from "styled-components";
import { getCategoryOption } from "@/api/category";
import { getTagOption } from "@/api/tag";
import { articleTypeMap, articleTypeOptions } from "@/constant/data";
import {
  deleteArticle,
  getArticles,
  softDeleteArticle,
  updateArticleTop,
} from "@/api/article";
import useGetState from "@/hooks/useGetState";
import { convertImgUrl } from "@/utils/MyFun";
import { downloadFile, formatDate } from "@/utils/common/common";
import useMyContext from "@/hooks/useContext";
import useCRUD from "@/hooks/useCRUD";
import { getToken } from "@/utils/auth";
const Styled = styled.div``;

const List = () => {
  const $table = useRef();
  const navigate = useNavigate();
  const token = getToken();
  const { handleDelete } = useCRUD({
    name: "文章",
    doDelete: updateOrDeleteArticles,
    refresh: () => $table.current.handleSearch(),
  });
  // 控制文章状态: 公开, 私密, 草稿箱, 回收站
  // const [extraParams, setExtraparams] = useState({});
  const [extraParams, setExtraparams, getExtraparams] = useGetState({});
  //分类配置
  const [categoryOptions, setCategoryOptions] = useState([]);
  //标签配置
  const [tagOptions, setTagOptions] = useState([]);
  //条件搜索
  const [queryItems, setQueryItems, getQueryItems] = useGetState({});
  const [loadingStates, setLoadingStates] = useState({});
  const [tableSelections, setTableSelections] = useState([]); //表格第一项全选数组
  const { messageApi } = useMyContext();
  //tab标签的配置
  const Tabitems = [
    {
      key: "all",
      label: "全部",
    },
    {
      key: "public",
      label: "公开",
    },
    {
      key: "secret",
      label: "私密",
    },
    {
      key: "draft",
      label: "草稿箱",
    },
    {
      key: "delete",
      label: "回收站",
    },
  ];

  //表格每列标题的配置
  const columns = [
    {
      title: "文章封面",
      key: "img",
      dataIndex: "img",
      width: 55,
      align: "center",
      render(text, record, index) {
        // text图片地址
        return (
          <Image
            src={convertImgUrl(text)}
            style={{ borderRadius: "2px", height: "100%", width: "100%" }}
            fallback="http://dummyimage.com/400x400"
          />
        );
      },
    },
    {
      title: "文章标题",
      key: "title",
      dataIndex: "title",
      width: 120,
      align: "center",
      ellipsis: { tooltip: true },
    },
    {
      title: "分类",
      key: "category.name",
      dataIndex: "category.name",
      width: 60,
      align: "center",
      ellipsis: { tooltip: true },
      render(text, record, index) {
        return <div>{record.name || "无"}</div>;
      },
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      width: 100,
      align: "center",
      render(text, record, index) {
        const tags = record.tag_names ?? [];
        const group = [];
        for (let i = 0; i < tags.length; i++) {
          group.push(
            <Tag
              key={i}
              color="processing"
              style={{ margin: "2px 3px", fontSize: "16px" }}
            >
              {tags[i]}
            </Tag>
          );
        }
        return <div> {group.length > 0 ? group : "无"} </div>;
      },
    },
    {
      title: "浏览量",
      key: "view_count",
      dataIndex: "view_count",
      width: 40,
      align: "center",
      ellipsis: { tooltip: true },
    },
    {
      title: "点赞量",
      key: "like_count",
      dataIndex: "like_count",
      width: 40,
      align: "center",
      ellipsis: { tooltip: true },
    },
    {
      title: "类型",
      key: "type",
      dataIndex: "type",
      width: 50,
      align: "center",
      render(text, record, index) {
        return (
          <Tag
            color={articleTypeMap[record.type].tag}
            style={{ fontSize: "16px" }}
          >
            {articleTypeMap[record.type].name}
          </Tag>
        );
      },
    },
    {
      title: "发布时间",
      key: "updateDate",
      dataIndex: "updateDate",
      align: "center",
      width: 80,
      render(text, record, index) {
        return (
          <Button
            type="link"
            icon={<FieldTimeOutlined />}
            size="small"
            style={{ color: "#333" }}
          >
            {formatDate(record.update_at)}
          </Button>
        );
      },
    },
    {
      title: "置顶",
      key: "is_top",
      dataIndex: "is_top",
      width: 50,
      align: "center",
      render(text, record, index) {
        return (
          <Switch
            loading={!!loadingStates[index]}
            size="small"
            checked={record.is_top === 1}
            onChange={() => {
              //指定逻辑，就是每次修改了值，后端查询根据置顶标志查询排序返回
              handleUpdateTop(record, index);
            }}
          />
        );
      },
    },
    {
      title: "操作",
      key: "actions",
      dataIndex: "actions",
      width: 120,
      align: "center",
      render(text, record, index) {
        return (
          <>
            {record.is_delete ? (
              <Button
                type="primary"
                icon={<EyeOutlined />}
                style={{
                  marginRight: "5px",
                }}
                onClick={async () => {
                  await softDeleteArticle({ ids: [record.id], is_delete: 0 });
                  await $table.current.handleSearch();
                }}
              >
                恢复
              </Button>
            ) : (
              <Button
                type="primary"
                icon={<EyeOutlined />}
                style={{
                  marginRight: "5px",
                }}
                onClick={() => {
                  //跳转页面进行编辑
                  navigate({
                    pathname: `/article/write/${record.id}`,
                  });
                }}
              >
                查看
              </Button>
            )}
            <Popconfirm
              title="确认删除该文章吗"
              description="删除后可在回收站中查看"
              onConfirm={() => {
                handleDelete([record.id]);
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                icon={<DeleteOutlined />}
                style={{ backgroundColor: "#D03050FF" }}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  // 切换标签页: [全部, 公开, 私密, 草稿箱, 回收站]
  function handleChangeTab(value) {
    switch (value) {
      case "all":
        setExtraparams({
          is_delete: 0,
          status: null,
        });
        break;
      case "public":
        setExtraparams({
          is_delete: 0,
          status: 1,
        });
        break;
      case "secret":
        setExtraparams({
          is_delete: 0,
          status: 2,
        });

        break;
      case "draft":
        setExtraparams({
          is_delete: 0,
          status: 3,
        });
        break;
      case "delete":
        setExtraparams({
          is_delete: 1,
          status: null,
        });
        break;
    }
    //执行默认搜索,初始化情况用于获取表格数据
    $table.current.handleSearch();
  }

  function updateQueryItems(newQueryItems) {
    console.log("更新query", newQueryItems);
    setQueryItems(newQueryItems);
  }

  //处理文章置顶
  async function handleUpdateTop(row, index) {
    //开启开关组件loading效果
    setLoadingStates({ ...loadingStates, [index]: true });
    //数据切换=》置顶1 => 0 未置顶0 => 1
    row.is_top = row.is_top === 0 ? 1 : 0;
    await updateArticleTop(row);
    setLoadingStates({ ...loadingStates, [index]: false });
    messageApi.open({
      type: "success",
      content: row.is_top ? "已成功置顶" : "已取消置顶",
    });
    //获取最新数据
    $table.current.handleSearch();
  }

  //is_delete为0软删除 1为物理删除
  async function updateOrDeleteArticles(ids) {
    return extraParams.is_delete === 0
      ? await softDeleteArticle({ ids, is_delete: 1 })
      : await deleteArticle(ids);
  }

  //导出函数
  function exportArticles(ids) {
    //从现有文章中，选出选中的文章
    const list = $table.current.dataSource.filter((e) => ids.includes(e.id));
    for (const item of list) {
      downloadFile(item.content, `${item.title}.md`);
    }
  }

  useEffect(() => {
    getCategoryOption().then((res) => {
      setCategoryOptions(res.data);
    });
    getTagOption().then((res) => {
      setTagOptions(res.data);
    });
    handleChangeTab("all"); // 默认查看全部
  }, []);

  return (
    <Styled>
      <CommonPage title="文章列表">
        {/* 操作栏部分，通过插槽传递 */}
        <div className="action-slot" slot="action">
          <Button
            type="primary"
            icon={<Add />}
            onClick={() => {
              navigate({ pathname: "/article/write" }, { replace: true });
            }}
          >
            新建文章
          </Button>
          <Button
            type="primary"
            danger
            icon={<DeleteOne />}
            disabled={tableSelections.length ? false : true}
            onClick={() => {
              //批量删除
              handleDelete(tableSelections);
            }}
          >
            批量删除
          </Button>
          <Button
            type="primary"
            style={{ backgroundColor: "skyblue" }}
            icon={<Exist />}
            disabled={tableSelections.length ? false : true}
            onClick={exportArticles.bind(null, tableSelections)}
          >
            批量导出
          </Button>
          {/* 采用文件上传 */}
          <Upload
            name="file"
            action="/api/article/import"
            headers={{ authorization: `Bearer ${token}` }}
            showUploadList={false}
            onChange={(info) => {
              if (info.file.status !== "uploading") {
                //进行文件校验
                const role = [".md"];
                const filename = info.file.name;
                for (let i = 0; i < role.length; i++) {
                  if (!filename.includes(role[i])) {
                    messageApi.error("请重新选择上传文件类型!");
                    return;
                  }
                }
              }
              if (info.file.status === "done") {
                const response = info.file.response;
                if (response.code === 0) {
                  messageApi.success("文件导入成功!");
                  $table.current.handleSearch();
                } else {
                  messageApi.error("文件导入失败!");
                }
              } else if (info.file.status === "error") {
                messageApi.error("文件导入失败!");
              }
            }}
          >
            <Button
              type="primary"
              style={{ backgroundColor: "green" }}
              icon={<Enter />}
            >
              批量导入
            </Button>
          </Upload>
        </div>
        {/* 导航栏 */}
        <Tabs
          defaultActiveKey="all"
          items={Tabitems}
          onChange={handleChangeTab}
        />
        {/* 表格 */}
        <CrudTable
          ref={$table}
          getData={getArticles}
          columns={columns}
          getExtraparams={getExtraparams}
          queryItems={queryItems}
          updateQueryItems={updateQueryItems}
          setTableSelections={setTableSelections}
          getQueryItems={getQueryItems}
        >
          <div className="queryBar-slot flex label-ml-15" slot="queryBar">
            <QueryBarItem label="标题" labelWidth={40} contentWidth={180}>
              <Input
                placeholder="请输入标题"
                value={queryItems.title}
                onChange={(e) => {
                  setQueryItems({
                    ...queryItems,
                    title: e.target.value,
                  });
                }}
              />
            </QueryBarItem>
            <QueryBarItem label="类型" labelWidth={40} contentWidth={160}>
              <Select
                style={{
                  width: "100%",
                }}
                allowClear
                placeholder="请选择文章类型"
                onChange={(val) => {
                  setQueryItems({
                    ...queryItems,
                    type: val,
                  });
                }}
                value={queryItems.type}
                options={articleTypeOptions}
              />
            </QueryBarItem>
            <QueryBarItem label="分类" labelWidth={40} contentWidth={160}>
              <Select
                style={{
                  width: "100%",
                }}
                allowClear
                placeholder="请选择文章分类"
                onChange={(val) => {
                  setQueryItems({
                    ...queryItems,
                    category_id: val,
                  });
                }}
                value={queryItems.category_id}
                options={categoryOptions}
              />
            </QueryBarItem>
            <QueryBarItem label="标签" labelWidth={40} contentWidth={160}>
              <Select
                style={{
                  width: "100%",
                }}
                allowClear
                placeholder="请选择文章标签"
                onChange={(val) => {
                  setQueryItems({
                    ...queryItems,
                    tag_id: val,
                  });
                }}
                value={queryItems.tag_id}
                options={tagOptions}
              />
            </QueryBarItem>
          </div>
        </CrudTable>
      </CommonPage>
    </Styled>
  );
};

export default List;
